package be.phl.mycinema.classes;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class DownloadImageTask extends AsyncTask<Object, Void, Bitmap> {

	ImageView iView;
	String key;
	String url;
	MemoryCache memoryCache;

	public DownloadImageTask(String url, String key, ImageView iView, MemoryCache memoryCache) {
		this.key = key;
		this.iView = iView;
		this.url = url;
		this.memoryCache = memoryCache;
	}

	@Override
	protected Bitmap doInBackground(Object... params) {
		try {
			Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(url).getContent());
			return bitmap;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	protected void onPostExecute(Bitmap result) {
		if (result != null) {
			iView.setImageBitmap(result);
			memoryCache.addBitmapToMemoryCache(key, result);
		}
	}
}
